<?php

namespace app\admin\model\yungift;


use think\Exception;

/**
 * 分组
 */
class Group extends \addons\yungift\model\Group
{
    // 自定义初始化
    protected static function init()
    {
        // 处理层级levels
        Group::event('before_write', function ($record) {
            $scenario = $record->data['scenario'] ?? null;
            if ($scenario) {
                if ($record->parent_id) {
                    if (! $parent = Group::get(['id' => $record->parent_id])) {
                        throw new Exception('父级分组不存在:' . $record->parent_id);
                    }
                    $record->levels = $parent->levels . '-' . $parent->id;
                } else {
                    $record->levels = 0;
                }
                if (count(explode('-', $record->levels)) >= 4) {
                    throw new Exception('最多支持三级分组');
                }
            }

            if (! empty($record->data['deleted_at'])) {
                if (Group::where(['parent_id' => $record->id])->count()) {
                    throw new Exception('"' . $record['name'] . '"存在子级分组，请先删除');
                }
                if (Member::where(['group_id' => $record->id])->count() > 0) {
                    throw new Exception('"' . $record['name'] . '"分组下存在成员，不支持删除');
                }
            }

            return true;
        });
    }
}
